According to the documentation,
A program may produce unpredictable results if it attempts to distinguish two references to equal values of a value-based class, whether directly
via reference equality or indirectly via an appeal to synchronization, identity hashing, serialization…
For example (credit to Brian Goetz), imagine Foo is a value-based class:
Foo[] arr = new Foo[2];
arr[0] = new Foo(0);
arr[1] = new Foo(0);
Serialization promises that on deserialization of arr, elements 0 and 1 will not be aliased. Similarly, in:
Foo[] arr = new Foo[2];
arr[0] = new Foo(0);
arr[1] = arr[0];
Serialization promises that on deserialization of arr
, elements 0 and 1 will be aliased.
While these promises are coincidentally fulfilled in current implementations of Java, that is not guaranteed in the future, particularly when true
value types are introduced in the language.
This rule raises an issue when a Serializable
class defines a non-transient, non-static field field whose type is a known serializable
value-based class. Known serializable value-based classes are: all the classes in the java.time
package except Clock
; the
date classes for alternate calendars: HijrahDate
, JapaneseDate
, MinguoDate
, ThaiBuddhistDate
.
Noncompliant code example
class MyClass implements Serializable {
private HijrahDate date; // Noncompliant; mark this transient
// ...
}
Compliant solution
class MyClass implements Serializable {
private transient HijrahDate date;
// ...
}